package com.wyf.android.advance

import android.app.Application
import com.tencent.mmkv.*
import com.wyf.android.baselib.util.LogUtil

class App : Application(), MMKVHandler, MMKVContentChangeNotification {
    override fun onCreate() {
        super.onCreate()

        //初始化MMKV

        //根目录 默认 filesDir.absolutePath + "/mmkv"
        val dir = filesDir.absolutePath + "/mmkv_yintech"
        val rootDir = MMKV.initialize(dir)
        LogUtil.d("rootDir: $rootDir")
        //设置日志等级
        MMKV.setLogLevel(MMKVLogLevel.LevelInfo)
        //注册处理器
        MMKV.registerHandler(this)
        //注册内容改变监听
        MMKV.registerContentChangeNotify(this)

    }

    override fun onTerminate() {
        MMKV.onExit()
        super.onTerminate()
    }

    override fun onMMKVCRCCheckFail(p0: String?): MMKVRecoverStrategic {
        LogUtil.d("onMMKVCRCCheckFail--$p0")
        return MMKVRecoverStrategic.OnErrorRecover
    }

    override fun onMMKVFileLengthError(p0: String?): MMKVRecoverStrategic {
        LogUtil.d("onMMKVCRCCheckFail--$p0")
        return MMKVRecoverStrategic.OnErrorRecover
    }

    override fun wantLogRedirecting(): Boolean {
        return BuildConfig.DEBUG
    }

    override fun mmkvLog(
        level: MMKVLogLevel?,
        file: String?,
        line: Int,
        func: String?,
        message: String?
    ) {
        val log = "<$file:$line::$func> $message"
        when (level) {
            MMKVLogLevel.LevelDebug -> LogUtil.d("redirect logging MMKV", log)
            MMKVLogLevel.LevelNone, MMKVLogLevel.LevelInfo -> LogUtil.i("redirect logging MMKV", log)
            MMKVLogLevel.LevelWarning -> LogUtil.w("redirect logging MMKV", log)
            MMKVLogLevel.LevelError -> LogUtil.e("redirect logging MMKV", log)
        }
    }

    /**
     * 其它进程改变数据回调
     */
    override fun onContentChangedByOuterProcess(p0: String?) {
        LogUtil.d("onContentChangedByOuterProcess--$p0")
    }
}